package com.css.fxfzfxqh.modules.reportmanagement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzfxqh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.EvaluationResults;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.LifelineTaskEntity;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.EstimateRepository;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.TaskManagementRepository;
import com.css.fxfzfxqh.modules.reportTemplate.entity.Template;
import com.css.fxfzfxqh.modules.reportmanagement.reportutil.CustomXWPFDocument;
import com.css.fxfzfxqh.modules.reportmanagement.repository.LifelineReportRepository;
import com.css.fxfzfxqh.modules.reportmanagement.service.ExportReportDataService;
import com.css.fxfzfxqh.modules.reportmanagement.service.GraphService;
import com.css.fxfzfxqh.modules.reportmanagement.service.LifelineReportService;
import com.css.fxfzfxqh.modules.reportmanagement.vo.CurRole;
import com.css.fxfzfxqh.modules.reportmanagement.vo.LifelineReportVo;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.RegexUtils;
import javafx.scene.Camera;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class LifelineReportServiceImpl implements LifelineReportService {
    @Autowired
    private LifelineReportRepository lifelineReportRepository;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SUserService sUserService;
    @Autowired
    private TaskManagementRepository taskManagementRepository;
    @Autowired
    private AttachmentInfoService attachmentInfoService;
    @Value("${image.localDir}")
    private String localDir;
    @Autowired
    private EstimateRepository estimateRepository;
    @Autowired
    private ExportReportDataServiceImpl exportReportDataServiceImpl;
    @Resource
    GraphService graphService;

    @Override
    public Map<String, Object> getAll(LifelineReportVo vo) {
        vo.setRole(getRole());
        return lifelineReportRepository.getAll(vo);
    }

    @Override
    public CurRole getCurRole() {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE))
            return new CurRole("0");
        if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
            if (PlatformObjectUtils.isEmpty(sUser.getProvinceId())) {
                throw new RuntimeException("请完善当前登陆人所属省市区信息");
            }
            return new CurRole("1", sUser.getProvinceId());
        }
        if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
            if (PlatformObjectUtils.isEmpty(sUser.getProvinceId()) || PlatformObjectUtils.isEmpty(sUser.getCityId())) {
                throw new RuntimeException("请完善当前登陆人所属省市区信息");
            }
            return new CurRole("2", sUser.getProvinceId(), sUser.getCityId());
        }
        if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
            if (PlatformObjectUtils.isEmpty(sUser.getProvinceId()) || PlatformObjectUtils.isEmpty(sUser.getCityId()) || PlatformObjectUtils.isEmpty(sUser.getCountyId())) {
                throw new RuntimeException("请完善当前登陆人所属省市区信息");
            }
            return new CurRole("3", sUser.getProvinceId(), sUser.getCityId(), sUser.getCountyId());
        }
        return new CurRole("0");
    }


    private String getRole() {
        String userId = PlatformSessionContext.getUserID();
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE))
            return "0";
        if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE))
            return "1";
        if (allRole.contains(FxfzConstants.PH_CITY_CODE))
            return "2";
        if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE))
            return "3";
        return "3";
    }


    @Override
    @Transactional
    public LifelineTaskEntity createReport(HttpServletResponse response, String id) throws Exception {
        LifelineTaskEntity entity = taskManagementRepository.getEntityById(id);
        String fileName = null;
        //读取上传的模板
        String srcDocxPath = getInputStream1(entity.getInputMethod());
        //String srcDocxPath = ("D:\\static\\2023\\11\\27\\生命线评估-设定烈度_1701066506360.docx");
        //从内路径template读取的模板
        //InputStream input = getInputStream2(entity.getInputMethod());

        if (entity.getInputMethod() == 1) fileName = "生命线评估-设定烈度.docx";
        if (entity.getInputMethod() == 2) fileName = "生命线评估-设定地震影响场.docx";
        //CustomXWPFDocument xwpfDocument = new CustomXWPFDocument(input);
        Map reportData = getReportData1(id, entity.getInputMethod());
        //writeData(xwpfDocument, reportData, id, entity.getInputMethod());
        String realFileName = getRealFileName(fileName);
        //获取文件上传的本地路径
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
        String savePath = localDir + dateDir;
        //判断文件夹是否存在如果不存在则创建
        if(!new File(savePath).exists()){
            new File(savePath).mkdirs();
        }

        String deskDocxPath=savePath+ File.separator+realFileName;
        LoopRowTableRenderPolicy rowTableRenderPolicy = new LoopRowTableRenderPolicy();
        try (

                InputStream inputStream = new FileInputStream(srcDocxPath)) {
            ConfigureBuilder builder = Configure.builder().bind("gsgwList",rowTableRenderPolicy)
                    .bind("gsbfList",rowTableRenderPolicy)
                    .bind("gsscList",rowTableRenderPolicy)
                    .bind("gqcqgList",rowTableRenderPolicy)
                    .bind("gqmzList",rowTableRenderPolicy)
                    .bind("gqgwList",rowTableRenderPolicy)
                    .bind("gdbdzList",rowTableRenderPolicy)
                    .bind("gddlxlList",rowTableRenderPolicy)
                    .bind("gdfdzList",rowTableRenderPolicy)
                    .bind("jtdlList",rowTableRenderPolicy)
                    .bind("jtqlList",rowTableRenderPolicy)
                    .bind("txjzList",rowTableRenderPolicy)
                    .bind("txsbList",rowTableRenderPolicy);//允许除了标签前后缀外的任意字符
            Configure config = builder.build();
            // 通过协查函模板，开始生成电子协查函
            try (
                    XWPFTemplate template = XWPFTemplate.compile(inputStream,config).render(reportData);
                    OutputStream outDocx = Files.newOutputStream(Paths.get(deskDocxPath))) {

                ZipSecureFile.setMinInflateRatio(-1D);
                // 输出word
                template.getXWPFDocument().write(outDocx);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        //保存到数据库
        String uuid = UUIDGenerator.getUUID();
        AttachmentInfoEntity attachmentInfoEntity = buildAttachment(uuid, fileName, dateDir, realFileName);
        attachmentInfoService.save(Arrays.asList(attachmentInfoEntity));
        return this.saveReport(id, uuid, fileName);
    }

    private InputStream getInputStream2(Integer inputMethod) {
        InputStream input1 = null;
        if (inputMethod == 1) input1 = ClassLoader.getSystemResourceAsStream("template/生命线评估-设定烈度.docx");
        if (inputMethod == 2) input1 = ClassLoader.getSystemResourceAsStream("template/生命线评估-设定地震影响场.docx");
        return input1;
    }

    private String getInputStream1(Integer inputMethod) throws Exception {
        Template template = null;
        if (inputMethod == 1) template = lifelineReportRepository.getTemplate("10000003", "1000000301");
        if (inputMethod == 2) template = lifelineReportRepository.getTemplate("10000003", "1000000302");
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(template.getAttachId());
        return (attach.getFileDirId() + attach.getAttachPath());
    }

    private Map getReportData1(String id, Integer inputMethod) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String user = sUserService.getSUser(PlatformSessionUtils.getUserId());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        map.put("unit", sUser.getOrgName());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        map.put("time", dateFormat.format(new Date()));
        map.put("assess_obj_flag_1",false);
        map.put("assess_obj_flag_2",false);
        map.put("assess_obj_flag_3",false);
        map.put("assess_obj_flag_4",false);
        map.put("assess_obj_flag_5",false);
        Map<String, Object> smxTaskObjById = graphService.getSmxTaskObjById(id);
        String evaluationObject = (String)smxTaskObjById.get("evaluation_object");
        if(evaluationObject.contains("1")){
            //供水
            map.put("assess_obj_flag_1",true);
        }
        if(evaluationObject.contains("2")){
            //供气
            map.put("assess_obj_flag_2",true);
        }
        if(evaluationObject.contains("3")){
            //供电
            map.put("assess_obj_flag_3",true);
        }
        if(evaluationObject.contains("4")){
        //交通
           map.put("assess_obj_flag_4",true);
        }
        if(evaluationObject.contains("5")){
            //通信
            map.put("assess_obj_flag_5",true);
        }
        map.put("gsgw",false);
        map.put("gsbf",false);
        map.put("gssc",false);
        map.put("gsexpire",false);
        //获取生命线各个系统选择的数据源
        List<String> typeList = estimateRepository.getTypeListByTaskId(id);
        Integer gs = 0;
        if(typeList.contains("1")){
            //地下管网
            map.put("gsgw",true);
            gs++;
        }
        if(typeList.contains("11")){
            //水厂泵房
            map.put("gsbf",true);
            gs++;
        }
        if(typeList.contains("2")){
            //水厂水池
            map.put("gssc",true);
            gs++;
        }
        if(gs>0){
            map.put("gsexpire",true);
        }
        //构建1、地下管网表数据
        List<EvaluationResults> gsgw = estimateRepository.getListByTaskIdAndType(id, 1);
        map.put("gsgwList",gsgw);
        //构建水厂泵房
        List<EvaluationResults> gsbf = estimateRepository.getListByTaskIdAndType(id, 11);
        map.put("gsbfList",gsbf);
        //构建水厂水池
        List<EvaluationResults> gssc = estimateRepository.getListByTaskIdAndType(id, 2);
        map.put("gsscList",gssc);
        map.put("gsgwList",gsgw);
        map.put("gqmqg",false);
        map.put("gqmz",false);
        map.put("gqgw",false);
        map.put("gqexpire",false);
        Integer gq = 0;
        if(typeList.contains("3")){
            //燃气-储气罐
            map.put("gqmqg",true);
            gq++;
        }
        if(typeList.contains("14")){
            //燃气-门站/场站
            map.put("gqmz",true);
            gq++;
        }
        if(typeList.contains("15")){
            //供气管网
            map.put("gqgw",true);
            gq++;
        }
        if(gq>0){
            map.put("gqexpire",true);
        }
        //构建燃气-储气罐
        List<EvaluationResults> gqcqg = estimateRepository.getListByTaskIdAndType(id, 3);
        map.put("gqcqgList",gqcqg);
        //构建燃气-门站/场站
        List<EvaluationResults> gqmz = estimateRepository.getListByTaskIdAndType(id, 14);
        map.put("gqmzList",gqmz);
        //构建供气管网
        List<EvaluationResults> gqgw = estimateRepository.getListByTaskIdAndType(id, 15);
        map.put("gqgwList",gqgw);
        map.put("gdbdz",false);
        map.put("gdfdz",false);
        map.put("gddlxl",false);
        map.put("gdexpire",false);
        Integer gd = 0;
        if(typeList.contains("6")){
            //变电站
            map.put("gdbdz",true);
            gd++;
        }
        if(typeList.contains("12")){
            //重要发电厂房
            map.put("gdfdz",true);
            gd++;
        }
        if(typeList.contains("8")){
            //电缆线路
            map.put("gddlxl",true);
            gd++;
        }
        if(gd>0){
            map.put("gdexpire",true);
        }
        //构建变电站
        List<EvaluationResults> gdbdz = estimateRepository.getListByTaskIdAndType(id, 6);
        map.put("gdbdzList",gdbdz);
        //构建重要发电厂房
        List<EvaluationResults> gdfdz = estimateRepository.getListByTaskIdAndType(id, 12);
        map.put("gdfdzList",gdfdz);
        //构建电缆线路
        List<EvaluationResults> gddlxl = estimateRepository.getListByTaskIdAndType(id, 8);
        map.put("gddlxlList",gddlxl);
        map.put("jtdl",false);
        map.put("jtql",false);
        map.put("jtexpire",false);
        Integer jt = 0;
        if(typeList.contains("5")){
            //道路
            map.put("jtdl",true);
            jt++;
        }
        if(typeList.contains("4")){
            //桥梁
            map.put("jtql",true);
            jt++;
        }
        if(jt>0){
            map.put("jtexpire",true);
        }
        //构建道路
        List<EvaluationResults> jtdl = estimateRepository.getListByTaskIdAndType(id, 5);
        map.put("jtdlList",jtdl);
        //构建桥梁
        List<EvaluationResults> jtql = estimateRepository.getListByTaskIdAndType(id, 4);
        List<EvaluationResults> jtqlLine = estimateRepository.getLineListByTaskIdAndType(id, 4);
        if(PlatformObjectUtils.isEmpty(jtql)){
            jtql = new ArrayList<>();
        }
        if(PlatformObjectUtils.isNotEmpty(jtqlLine)){
            jtql.addAll(jtqlLine);
        }
        map.put("jtqlList",jtql);
        map.put("txjz",false);
        map.put("txsb",false);
        map.put("txexpire",false);
        Integer tx = 0;
        if(typeList.contains("13")){
            //通信基站
            map.put("txjz",true);
            tx++;
        }
        if(typeList.contains("9")){
            //通信室内设备
            map.put("txsb",true);
            tx++;
        }
        if(tx>0){
            map.put("txexpire",true);
        }
        //构建通信基站
        List<EvaluationResults> txjz = estimateRepository.getListByTaskIdAndType(id, 13);
        map.put("txjzList",txjz);
        //通信室内设备
        List<EvaluationResults> txsb = estimateRepository.getListByTaskIdAndType(id, 9);
        map.put("txsbList",txsb);
        exportReportDataServiceImpl.getReportPicture(map, id, inputMethod);
        return map;
    }

    @Override
    public void uploadReport(LifelineTaskEntity entity) {
        lifelineReportRepository.saveUploadReport(entity);
    }

    private LifelineTaskEntity saveReport(String id, String reportId, String reportName) {
        LifelineTaskEntity entity = new LifelineTaskEntity();
        entity.setId(id);
        entity.setCreateReport(reportId);
        entity.setCreateReportName(reportName);
        entity.setCreateReportTime(PlatformDateUtils.getCurrentTimestamp());
        String user = sUserService.getSUser(PlatformSessionUtils.getUserId());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        entity.setCreateReportUser(sUser.getUserName());
        lifelineReportRepository.saveReport(entity);
        return entity;
    }

    private String getRealFileName(String fileName) {
        String preFileName = fileName.substring(0, fileName.lastIndexOf("."));
        // .jpg  .pdf  .txt  .docs
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 拼文件名  真实的文件名称
        String realFileName = preFileName + "_" + System.currentTimeMillis() + fileType;
        return realFileName;
    }

    private AttachmentInfoEntity buildAttachment(String uuid, String fileName, String dateDir, String realFileName) {
        AttachmentInfoEntity attachmentInfoEntity = new AttachmentInfoEntity();
        attachmentInfoEntity.setAttachId(uuid);
        attachmentInfoEntity.setAttachName(fileName);
        attachmentInfoEntity.setAttachPath(dateDir + "/" + realFileName);
        attachmentInfoEntity.setFileDirId(localDir);
        attachmentInfoEntity.setIsValid("1");
        attachmentInfoEntity.setIsCompleted("1");
        return attachmentInfoEntity;
    }

    private void writeData(CustomXWPFDocument xwpfDocument, Map reportData, String id, Integer inputMethod) {
        //替换段落字段和图片
        replaceInPara(xwpfDocument, reportData);
        //表格
        createTable(xwpfDocument, id, inputMethod);
        handler(xwpfDocument);
    }

    private void handler(CustomXWPFDocument xwpfDocument) {
        List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            String paragraphText1 = paragraph.getParagraphText();
            if (paragraphText1.contains("image")) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    run.setText("", 0);
                }
            }
        }

    }

    private void createTable(CustomXWPFDocument xwpfDocument, String id, Integer inputMethod) {
        Map<String, List<List<String>>> tableData = getTableData(id, inputMethod);
        List<XWPFTable> tables = xwpfDocument.getTables();
        List<List<String>> list1 = tableData.get("tableData1");
        if (ListUtils.isNotEmpty(list1)) WordUtil.insertTable1(tables.get(0), list1);
        List<List<String>> list2 = tableData.get("tableData2");
        if (ListUtils.isNotEmpty(list2)) WordUtil.insertTable1(tables.get(1), list2);
        List<List<String>> list3 = tableData.get("tableData3");
        if (ListUtils.isNotEmpty(list3)) WordUtil.insertTable1(tables.get(2), list3);
        List<List<String>> list4 = tableData.get("tableData4");
        if (ListUtils.isNotEmpty(list4)) WordUtil.insertTable1(tables.get(3), list4);
        List<List<String>> list5 = tableData.get("tableData5");
        if (ListUtils.isNotEmpty(list5)) WordUtil.insertTable1(tables.get(4), list5);
        List<List<String>> list6 = tableData.get("tableData6");
        if (ListUtils.isNotEmpty(list6)) WordUtil.insertTable1(tables.get(5), list6);
        List<List<String>> list7 = tableData.get("tableData7");
        if (ListUtils.isNotEmpty(list7)) WordUtil.insertTable1(tables.get(6), list7);
        List<List<String>> list8 = tableData.get("tableData8");
        if (ListUtils.isNotEmpty(list8)) WordUtil.insertTable1(tables.get(7), list8);
        List<List<String>> list9 = tableData.get("tableData9");
        if (ListUtils.isNotEmpty(list9)) WordUtil.insertTable1(tables.get(8), list9);
        List<List<String>> list10 = tableData.get("tableData10");
        if (ListUtils.isNotEmpty(list10)) WordUtil.insertTable1(tables.get(9), list10);
        List<List<String>> list11 = tableData.get("tableData11");
        if (ListUtils.isNotEmpty(list11)) WordUtil.insertTable1(tables.get(10), list11);
        List<List<String>> list12 = tableData.get("tableData12");
        if (ListUtils.isNotEmpty(list12)) WordUtil.insertTable1(tables.get(11), list12);
        List<List<String>> list13 = tableData.get("tableData13");
        if (ListUtils.isNotEmpty(list13)) WordUtil.insertTable1(tables.get(12), list13);
    }

    private Map<String, List<List<String>>> getTableData(String id, Integer inputMethod) {
        HashMap<String, List<List<String>>> map = new HashMap<>();
        List<EvaluationResults> list = estimateRepository.getListByTaskId(id);
        //地下管网
        List<EvaluationResults> results1 = list.stream().filter(s -> s.getType() == 1).collect(Collectors.toList());
        //水厂泵房
        List<EvaluationResults> results2 = list.stream().filter(s -> s.getType() == 11).collect(Collectors.toList());
        //水厂水池
        List<EvaluationResults> results3 = list.stream().filter(s -> s.getType() == 2).collect(Collectors.toList());
        //燃气储气罐
        List<EvaluationResults> results4 = list.stream().filter(s -> s.getType() == 3).collect(Collectors.toList());
        //燃气-门站/场站 14
        List<EvaluationResults> results5 = list.stream().filter(s -> s.getType() == 14).collect(Collectors.toList());
        //供气管网 15
        List<EvaluationResults> results6 = list.stream().filter(s -> s.getType() == 15).collect(Collectors.toList());
        //变电站 6
        List<EvaluationResults> results7 = list.stream().filter(s -> s.getType() == 6).collect(Collectors.toList());
        //电缆线路 8
        List<EvaluationResults> results8 = list.stream().filter(s -> s.getType() == 8).collect(Collectors.toList());
        //重要发电厂房 12
        List<EvaluationResults> results9 = list.stream().filter(s -> s.getType() == 12).collect(Collectors.toList());
        //道路 5
        List<EvaluationResults> results10 = list.stream().filter(s -> s.getType() == 5).collect(Collectors.toList());
        //桥梁 4
        List<EvaluationResults> results11 = list.stream().filter(s -> s.getType() == 4).collect(Collectors.toList());
        //通信基站 13
        List<EvaluationResults> results12 = list.stream().filter(s -> s.getType() == 13).collect(Collectors.toList());
        //通信室内设备 9
        List<EvaluationResults> results13 = list.stream().filter(s -> s.getType() == 9).collect(Collectors.toList());

        if (results1.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results1) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData1", lists);
        }
        if (results2.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results2) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getLongitude());
                list1.add(results.getLatitude());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData2", lists);
        }
        if (results3.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results3) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                list1.add(results.getExtends6());
                list1.add(results.getExtends7());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData3", lists);
        }
        if (results4.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results4) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getLongitude());
                list1.add(results.getLatitude());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData4", lists);
        }
        if (results5.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results5) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData5", lists);
        }
        if (results6.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results6) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData6", lists);
        }
        if (results7.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results7) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getLongitude());
                list1.add(results.getLatitude());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData7", lists);
        }
        if (results8.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results8) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData8", lists);
        }
        if (results9.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results9) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getLongitude());
                list1.add(results.getLatitude());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData9", lists);
        }
        if (results10.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results10) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                list1.add(results.getExtends6());
                list1.add(results.getExtends7());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData10", lists);
        }
        if (results11.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results11) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getLongitude());
                list1.add(results.getLatitude());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                list1.add(results.getExtends6());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData11", lists);
        }
        if (results12.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results12) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData12", lists);
        }
        if (results13.size() != 0) {
            List<List<String>> lists = new ArrayList<>();
            for (EvaluationResults results : results13) {
                List<String> list1 = new ArrayList<>();
                list1.add(results.getExtends1());
                list1.add(results.getExtends2());
                list1.add(results.getExtends3());
                list1.add(results.getExtends4());
                list1.add(results.getExtends5());
                list1.add(results.getExtends6());
                list1.add(results.getExtends7());
                if (inputMethod == 1) {
                    list1.add(results.getDisasterRate6State());
                    list1.add(results.getDisasterRate7State());
                    list1.add(results.getDisasterRate8State());
                    list1.add(results.getDisasterRate9State());
                    list1.add(results.getDisasterRate10State());
                } else list1.add(results.getDisasterRateState());
                lists.add(list1);
            }
            map.put("tableData13", lists);
        }
        return map;
    }

    private void replaceInPara(CustomXWPFDocument xwpfDocument, Map reportData) {
        Iterator<XWPFParagraph> iterator = xwpfDocument.getParagraphsIterator();
        XWPFParagraph para;
        //center是为了给标题加粗
        int center = 0;
        while (iterator.hasNext()) {
            para = iterator.next();
            para.setWordWrapped(true);
            //行间距
            //para.setSpacingBefore(100);
            center = this.replaceInPara(para, reportData, xwpfDocument, center);
        }
    }

    private int replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc, int center) {

        List<XWPFRun> runs;
        Matcher matcher;
        String paragraphText = para.getParagraphText();
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int temp = 0;
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                int fontSize = run.getFontSize();
                fontSize = getFontSize(fontSize);
                String fontFamily = run.getFontFamily();
                String runText = run.toString().trim();
                if ("".equals(runText)) {
                    continue;
                }
                if (runText.contains("{") && !runText.contains("}") && runText.length() > 1) {
                    runText = runText + "}";
                }
                if ("{".equals(runText)) {
                    temp = 1;
                }

                if (temp == 1) {
                    if (!"{".equals(runText) && !"}".equals(runText)) {
                        runText = "{" + runText + "}";
                        temp = 0;
                    }
                }
                boolean contains = runText.contains("{");
                if (!runText.contains("{") && !runText.contains("}")) {
                    continue;
                }
                //获取{}中的值
                int firstIndex = runText.indexOf("{");
                int endIndex = runText.indexOf("}");
                int lastIndex = runText.lastIndexOf("}");
                if (firstIndex != -1 && firstIndex + 1 == endIndex) {
                    continue;
                }
                if (endIndex != lastIndex) {
                    //表示存在多个{}
                    //分别获取每一个{}中的值runText
                    List<String> keys = getEveryKey(runText);
                    if (PlatformObjectUtils.isNotEmpty(keys)) {
                        for (String key : keys) {
                            Object o = params.get(key);
                            if (PlatformObjectUtils.isEmpty(o)) {
                                runText = runText.replace("{" + key + "}", "");
                            } else {
                                runText = runText.replace("{" + key + "}", o.toString());
                            }
                        }
                        para.removeRun(i);
                        XWPFRun xwpfRun = para.insertNewRun(i);
                        xwpfRun.setFontSize(fontSize);
                        xwpfRun.setFontFamily("".equals(fontFamily) ? "Times New Roman" : fontFamily);
                        if (para.getParagraphText().contains("title")) {
                            xwpfRun.setFontSize(fontSize);
                            xwpfRun.setFontFamily("".equals(fontFamily) ? "Times New Roman" : fontFamily);
                            xwpfRun.setBold(true);
                        }
                        xwpfRun.setText(runText);
                        break;
                    }
                } else {
                    if (firstIndex > -1 || endIndex > -1) {
                        if (runText.startsWith("{image-")) {
                            runText = runText.replace("{", "").replace("}", "");
                            String[] split = runText.split(",");
                            if (split.length == 2 && StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
                                try {
                                    List<String> imgurls = (List<String>) params.get(split[1]);
                                    int a = 0;
                                    for (String imgurl : imgurls) {
                                        String picType = null;
                                        String[] split1 = imgurl.split(",");
                                        imgurl = split1[1];
                                        if (imgurl.contains(".")) {
                                            picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
                                        }
                                        InputStream inputStream = new FileInputStream(imgurl);
                                        int width = Units.toEMU(Double.parseDouble("600"));
                                        int height = Units.toEMU(Double.parseDouble("400"));
                                        run.setText("\t", a);
                                        a = a + 3;
                                        run.addPicture(inputStream, getPictureType(picType), "", width, height);
                                        run.setText("\r\n");
                                        run.setText(split1[0] + "\r\n");
                                        para.setAlignment(ParagraphAlignment.CENTER);
//                                        run.setText("\r\n");
                                        run.setBold(true);
                                    }
                                } catch (IOException | InvalidFormatException e) {

                                }
                            } else {
                                try {
                                    runText = runText.split("-")[1];
                                    run.setText("\t\t\t\t\t\t");
                                    String imgurl = "";
                                    try{
                                        imgurl = (String) params.get(runText);
                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }

                                    if (PlatformObjectUtils.isNotEmpty(imgurl)) {
                                        String picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
                                        InputStream inputStream = new FileInputStream(imgurl);
                                        int width = Units.toEMU(Double.parseDouble("600"));
                                        int height = Units.toEMU(Double.parseDouble("400"));
                                        run.addPicture(inputStream, getPictureType(picType), "", width, height);
                                    }

                                } catch (InvalidFormatException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            center++;
                            if ("{".equals(runText) || "}".equals(runText)) {
                                runText = "";
                            } else {
                                String key = runText.substring(firstIndex + 1, endIndex);
                                Object o = params.get(key);
                                if (PlatformObjectUtils.isEmpty(o) || "".equals(o)) {
                                    runText = runText.replace("{" + key + "}", "");
                                } else {
                                    runText = runText.replace("{" + key + "}", o.toString());
                                }
                            }
                            para.removeRun(i);
                            XWPFRun xwpfRun = para.insertNewRun(i);
                            xwpfRun.setFontSize(fontSize);
                            xwpfRun.setFontFamily(fontFamily);
                            if (center == 1 || center == 2) {
                                xwpfRun.setBold(true);
                            }
                            xwpfRun.setText(runText);
                        }
                        //break;
                    }
                }
            }
        }
        return center;
    }

    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    private int getFontSize(int fontSize) {
        if (fontSize == 26) return 26;
        if (fontSize == 22) return 22;
        if (fontSize == 20) return 20;
        if (fontSize == 18) return 18;
        if (fontSize == 16) return 16;
        return 14;
    }

    private List<String> getEveryKey(String runText) {
        if(runText.contains("image-smx_destroy_11_yxc")){
           return null;
        }
        List<Integer> list = new ArrayList<>();
        List<String> keyList = new ArrayList<>();
        char[] chars = runText.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '{') {
                list.add(++i);
            }
            if (chars[i] == '}') {
                list.add(i);
            }
        }
        StringBuilder key = new StringBuilder("");
        for (int i = 0; i < list.size(); i++) {
            try{
                key.append(runText.substring(list.get(i), list.get(++i)));
            }catch (Exception ex){
                ex.printStackTrace();
            }

            keyList.add(key.toString());
            key = new StringBuilder("");
        }

        return keyList;
    }

    private static int getPictureType(String picType) {
        int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if (picType.equalsIgnoreCase("png")) {
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;
            } else if (picType.equalsIgnoreCase("dib")) {
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;
            } else if (picType.equalsIgnoreCase("emf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;
            } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
            } else if (picType.equalsIgnoreCase("wmf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }
}
